from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import BookSerializer
from .models import Books


class BookView(APIView):
    def get(self, request):
        obj = Books.objects.all()
        ser = BookSerializer(obj, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '添加成功', 'result': ser.data})
        else:
            return Response({'code': 101, 'msg': '添加失败', 'result': ser.errors})


class BookDetailView(APIView):
    def put(self, request, pk):
        obj = Books.objects.filter(pk=pk).first()
        if not obj:
            return Response({'code': 104, 'msg': '书籍不存在'})
        ser = BookSerializer(instance=obj, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功', 'result': ser.data})
        else:
            return Response({'code': 101, 'msg': '修改失败', 'result': ser.errors})

    def get(self, request, pk):
        obj = Books.objects.filter(pk=pk).first()
        if not obj:
            return Response({'code': 104, 'msg': '书籍不存在'})
        ser = BookSerializer(instance=obj)
        return Response({'code': 100, 'msg': '查看成功', 'result': ser.data})

    def delete(self, request, pk):
        Books.objects.filter(pk=pk).delete()
        return Response({'code': 100, 'msg': '删除成功'})
